package com.itheima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import com.itheima.wemedia.pojo.WmUser;
import com.itheima.wemedia.mapper.WmUserMapper;
import com.itheima.wemedia.service.WmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @description <p>自媒体用户信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.wemedia.service.impl
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {

    @Override
    public Map<String, Object> loginCheck(Map<String, String> map) {
        //参数校验
        String name = map.get("name");
        String password = map.get("password");
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)){
            throw new LeadNewsException("用户名或密码错误");
        }
        //根据用户名查
        WmUser wmUser = query().eq("name", name).one();
        if (wmUser==null){
            throw new LeadNewsException("用户名或密码错误");
        }
        log.debug("密码校验");
        String encryptedPwd = DigestUtils.md5DigestAsHex((password + wmUser.getSalt()).getBytes());
        if(!wmUser.getPassword().equals(encryptedPwd)){
            throw new LeadNewsException("用户名或密码错误!");
        }
        String token = AppJwtUtil.createToken(wmUser.getId().longValue());
        //6. 构建结果并返回
        Map<String, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("user", wmUser);
        return result;

    }

//    public static void main(String[] args) {
//        String encryptedPwd = DigestUtils.md5DigestAsHex(("adminabc123").getBytes());
//        System.out.println("encryptedPwd = " + encryptedPwd);
//    }
}
